//
//  XDXSocket.m
//  location
//
//  Created by Dongxiang Xu on 2024/9/8.
//

#import "XDXSocket.h"
#import "PSWebSocket.h"

static XDXSocket *shareInstance = nil;
@interface XDXSocket ()<PSWebSocketDelegate>

@property (nonatomic, strong) PSWebSocket *socket;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) NSTimer *closeTimer;

@end

@implementation XDXSocket

+ (instancetype)shareInstance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (shareInstance == nil) {
            shareInstance = [[self alloc] init];
        }
    });
    return shareInstance;
}

- (void)connect
{
    if (!_canSend && _userId.integerValue>0) {
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"ws://%@/ws/%@",IP,_userId]]];
        [request addValue:[XDXShareInstance shareInstance].access_token forHTTPHeaderField:@"Authorization"];
        self.socket = [PSWebSocket clientSocketWithRequest:request];
        self.socket.delegate = self;
        [self.socket open];
    }
}

- (void)setUserId:(NSString *)userId
{
    _userId = userId;
    [self connect];
}

- (void)webSocket:(PSWebSocket *)webSocket didFailWithError:(NSError *)error
{
    _canSend = NO;
    if (self.XDXSocketOpenBlock) {
        self.XDXSocketOpenBlock(NO);
    }
    
    [self.closeTimer invalidate];
    self.closeTimer = nil;
    self.closeTimer = [NSTimer scheduledTimerWithTimeInterval:10.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
        [self connect];
    }];
    [[NSRunLoop currentRunLoop] addTimer:self.closeTimer forMode:NSDefaultRunLoopMode];
}

- (void)setCanSend:(BOOL)canSend
{
    if (canSend==NO) {
        _canSend = NO;
        [self.socket close];
    }
}

- (void)close
{
    self.userId = @"";
    [self.socket close];
}

- (void)webSocketDidOpen:(PSWebSocket *)webSocket
{
    _canSend = YES;
    [self.closeTimer invalidate];
    self.closeTimer = nil;
    if (self.XDXSocketOpenBlock) {
        self.XDXSocketOpenBlock(YES);
    }
}

- (void)webSocket:(PSWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean
{
    NSLog(@"WebSocket 关闭 - 代码: %ld, 原因: %@, 是否干净关闭: %@", (long)code, reason, wasClean ? @"是" : @"否");
    _canSend = NO;
    [self.closeTimer invalidate];
    self.closeTimer = nil;
    self.closeTimer = [NSTimer scheduledTimerWithTimeInterval:60.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
        [self connect];
    }];
    [[NSRunLoop currentRunLoop] addTimer:self.closeTimer forMode:NSDefaultRunLoopMode];
}

- (void)webSocket:(PSWebSocket *)webSocket didReceiveMessage:(id)message
{
    if ([message isKindOfClass:[NSString class]]) {
        if ([message containsString:@"location_update_success"]) {
            [self.timer invalidate];
            self.timer = nil;
        }
        
        NSData *jsonData = [message dataUsingEncoding:NSUTF8StringEncoding];
        NSError *error = nil;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
        if (dic && self.XDXSocketReceiveBlock) {
            self.XDXSocketReceiveBlock(dic);
        }
    }
}

- (void)sendMessage:(NSObject *)message
{
    if (_canSend) {
        if ([message isKindOfClass:[NSDictionary class]]) {
            @autoreleasepool {
                // 将NSDictionary转换为JSON数据
                NSError *error;
                NSData *jsonData = [NSJSONSerialization dataWithJSONObject:message options:0 error:&error];
                
                // 将JSON数据转换为字符串
                NSString *jsonString;
                if (jsonData) {
                    jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
                } else {
                    jsonString = [NSString stringWithFormat:@"%@", error];
                }
                [self.socket send:jsonString];
                
                if ([jsonString containsString:@"location_update"]) {
                    [self.timer invalidate];
                    self.timer = nil;
                    self.timer = [NSTimer scheduledTimerWithTimeInterval:30.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
                        NSLog(@"心跳重启socket___%@",[XDXTimeTool getNowTimeTimestamp]);
                        self.canSend = NO;
                        [self connect];
                    }];
                    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
                }
            }
        }
    }
}

@end
